package com.message;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.google.protobuf.GeneratedMessageV3;

/**
 * protobuf消息管理
 * 
 * @author zhoufang
 *
 *         2018年1月17日 下午3:36:49
 */
public class ProtobufManager {

	/**
	 * key: actionId value: protobuf.class
	 */
	private Map<Integer, Class<? extends GeneratedMessageV3>> actionClazzMap = new HashMap<>();

	public void addMessage(int actionId, Class<? extends GeneratedMessageV3> clazz) {
		actionClazzMap.put(actionId, clazz);
	}

	public GeneratedMessageV3 parseByte(int actionId, byte[] bytes) {
		Class<? extends GeneratedMessageV3> clazz = actionClazzMap.get(actionId);
		if (clazz == null) {
			return null;
		}
		try {
			Method method = clazz.getMethod("parseFrom", new Class[] { byte[].class });
			GeneratedMessageV3 invoke = (GeneratedMessageV3) method.invoke(null, bytes);
			return invoke;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
}
